package com.cloud.wms.ui.inside.fragment;

import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatImageView;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.core.eventBus.Event;
import com.cloud.core.utils.NumberUtils;
import com.cloud.core.widget.decoration.GridItemDecoration;
import com.cloud.core.widget.decoration.LinearVerticalDecoration;
import com.cloud.widget.ScanText;
import com.cloud.widget.expand.ExpandLayout;
import com.cloud.widget.utils.DensityUtils;
import com.cloud.wms.R;
import com.cloud.wms.base.BaseViewPagerFragment;
import com.cloud.wms.config.EventConfig;
import com.cloud.wms.ui.common.activity.SelectBatchActivity;
import com.cloud.wms.ui.inside.contract.ReplenishDownContract;
import com.cloud.wms.ui.inside.entity.ReplenishBindEntity;
import com.cloud.wms.ui.inside.entity.ReplenishCommodityEntity;
import com.cloud.wms.ui.inside.presenter.ReplenishDownPresenter;
import com.cloud.wms.ui.inside.replenish.ReplenishUpActivity;
import com.cloud.wms.ui.main.entity.BatchEntity;
import com.cloud.wms.ui.main.entity.PosEntity;
import com.cloud.wms.ui.main.entity.TaskEntity;
import com.cloud.wms.widget.dialog.TaskCompleteDialog;
import com.trello.rxlifecycle3.LifecycleTransformer;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author:Chen
 * @Date: 2021-03-07 16:10
 * @Description:
 */
public class ReplenishDownFragment extends BaseViewPagerFragment<ReplenishDownPresenter> implements ReplenishDownContract.View {
    @BindView(R.id.scan_text)
    ScanText scanText;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.ll_pos_content)
    LinearLayout llPosContent;
    @BindView(R.id.tv_commodity_name)
    TextView tvCommodityName;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.ll_btn)
    LinearLayout llBtn;
    @BindView(R.id.tv_commodity_code)
    TextView tvCommodityCode;
    @BindView(R.id.iv_select_batch)
    AppCompatImageView ivSelectBatch;
    @BindView(R.id.iv_toggle_batch)
    AppCompatImageView ivToggleBatch;
    @BindView(R.id.rv_batch_list)
    RecyclerView rvBatchList;
    @BindView(R.id.expand_layout)
    ExpandLayout expandLayout;
    @BindView(R.id.tv_plan_amount)
    TextView tvPlanAmount;
    @BindView(R.id.tv_down_amount)
    TextView tvDownAmount;
    @BindView(R.id.et_commodity_amount)
    EditText etCommodityAmount;
    @BindView(R.id.nestedScrollView)
    NestedScrollView nestedScrollView;
    @BindView(R.id.tv_pos_code)
    TextView tvPosCode;
    @BindView(R.id.btn_part)
    CheckedTextView btnPart;
    @BindView(R.id.btn_all)
    CheckedTextView btnAll;
    @BindView(R.id.btn_submit_and_shelf)
    TextView btnSubmitAndShelf;
    @BindView(R.id.tv_pos_setting)
    TextView tvPosSetting;
    @BindView(R.id.tv_batch_amount)
    TextView tvBatchAmount;
    private ReplenishBindEntity bindInfoEntity;
    private TaskEntity taskEntity;
    private BaseQuickAdapter<PosEntity, BaseViewHolder> mAdapter;
    private ReplenishCommodityEntity commodityEntity;
    private ArrayList<BatchEntity> posBatchEntity;
    private BaseQuickAdapter<BatchEntity, BaseViewHolder> mBatchAdapter;
    private String scanPosCode;

    @Override
    protected int getResId() {
        return R.layout.fragment_inside_replenish_down;
    }

    @Override
    protected void setupComponent() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void initEvent(Bundle bundle) {
        bindInfoEntity = getArguments().getParcelable("OrderInfoEntity");
        taskEntity = getArguments().getParcelable("Task");

        etCommodityAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String amountStr = s.toString();
                if (s.length() > 1 && s.toString().startsWith("0")) {
                    amountStr = s.toString().replaceFirst("0", "");
                    etCommodityAmount.setText(amountStr);
                }
                verifyData(false);
            }
        });

        rvList.setLayoutManager(new GridLayoutManager(getContext(), 3));
        mAdapter = new BaseQuickAdapter<PosEntity, BaseViewHolder>(R.layout.item_replenish_rec_pos) {
            @Override
            protected void convert(BaseViewHolder helper, PosEntity item) {
                helper.setText(R.id.tv_pos_code, item.getPosCode());
            }
        };
        rvList.setItemAnimator(new DefaultItemAnimator());
        rvList.addItemDecoration(GridItemDecoration.newBuilder().spanCount(3)
                .verticalDivider(ContextCompat.getDrawable(getContext(), R.color.bg_base_content), DensityUtils.Dp2Px(getContext(), 6), false)
                .horizontalDivider(ContextCompat.getDrawable(getContext(), R.color.bg_base_content), DensityUtils.Dp2Px(getContext(), 6), false)
                .build());
        rvList.setAdapter(mAdapter);

        rvBatchList.setLayoutManager(new LinearLayoutManager(getContext()));
        mBatchAdapter = new BaseQuickAdapter<BatchEntity, BaseViewHolder>(R.layout.item_common_select_batch) {
            @Override
            protected void convert(BaseViewHolder helper, BatchEntity item) {
                helper.setText(R.id.tv_produce_date, item.getProductionDate())
                        .setText(R.id.tv_deadline_date, item.getExpirationDate())
                        .setText(R.id.tv_in_date, item.getInDate());
            }
        };
        rvBatchList.setItemAnimator(new DefaultItemAnimator());
        rvBatchList.addItemDecoration(new LinearVerticalDecoration(DensityUtils.Dp2Px(getContext(), 10)));
        rvBatchList.setAdapter(mBatchAdapter);

        expandLayout.setOnExpansionUpdateListener((expansionFraction, state) -> {
            ivToggleBatch.setRotation(expansionFraction * 90);
        });

        mPresenter.loadReplenishCommodity(taskEntity.getBillID());
    }

    @Override
    public ScanText getScanText() {
        return scanText;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onScanHandle(String result, int resultCode) {
        super.onScanHandle(result, resultCode);
        scanText.addHistory(result);
        if (TextUtils.isEmpty(tvPosCode.getText().toString())) {
            scanPosCode = result;
            mPresenter.checkDownPosCode(taskEntity.getBillID(), result, commodityEntity.getCommodityId(), commodityEntity.getStockType());
        } else {
            if (commodityEntity.matchBarCode(result)) {
                tvCommodityCode.setTag(true);
                success("条码扫描成功，请录入数量！");
                verifyData(false);
            } else {
                info("条码扫描验证失败！");
            }
        }
    }

    private void verifyData(boolean isShowTips) {
        Object tag = tvCommodityCode.getTag();
        if (tag == null || !((boolean) tag)) {
            btnSubmit.setEnabled(false);
            btnSubmitAndShelf.setEnabled(false);
            if (isShowTips) info("请扫描商品！");
            return;
        }
        if (mBatchAdapter.getData().isEmpty()) {
            btnSubmit.setEnabled(false);
            btnSubmitAndShelf.setEnabled(false);
            if (isShowTips) info("请选择批次！");
            return;
        }
        int amount = NumberUtils.getIntegerValue(etCommodityAmount.getText().toString());
        if (amount <= 0) {
            btnSubmit.setEnabled(false);
            btnSubmitAndShelf.setEnabled(false);
            if (isShowTips) info("请输入补货下架数量！");
            return;
        }
        btnSubmit.setEnabled(true);
        btnSubmitAndShelf.setEnabled(true);
    }

    @Override
    public void onSuccess(Message message) {
        switch (message.what) {
            case ReplenishDownPresenter.REPLENISH_COMMODITY:
                commodityEntity = ((ReplenishCommodityEntity) message.obj);
                setDataToView(commodityEntity);
                break;
            case ReplenishDownPresenter.CHECK_DOWN_POS:
                posBatchEntity = ((ArrayList<BatchEntity>) message.obj);
                tvPosCode.setText(scanPosCode);
                commodityEntity.setPosCode(scanPosCode);
                scanText.setHint("商品条码");
                if (posBatchEntity.size() == 1) {
                    setBatchToView(posBatchEntity);
                    success("库位扫描成功，请扫描商品录入数量！");
                    ivSelectBatch.setVisibility(View.GONE);
                } else {
                    ivSelectBatch.setVisibility(View.VISIBLE);
                    success("库位扫描成功，请扫描商品选择批次！");
                }
                break;
            case ReplenishDownPresenter.GO_REPLENISH_SHELF:
                ReplenishUpActivity.start(getContext(), taskEntity);
                getActivity().finish();
                break;
            case ReplenishDownPresenter.REPLENISH_DOWN_COMPLETE:
                TaskCompleteDialog dialog = new TaskCompleteDialog(getActivity());
                dialog.show();
                dialog.setOnNextListener(
                        () -> {
                            ReplenishUpActivity.start(getContext(), taskEntity);
                            getActivity().finish();
                            dialog.dismiss();
                        },
                        "立即去上架");
                break;
        }
    }

    private void setDataToView(ReplenishCommodityEntity commodityBean) {
        tvPosCode.setText("");
        etCommodityAmount.setText("");
        mAdapter.getData().clear();
        mAdapter.notifyDataSetChanged();
        mBatchAdapter.getData().clear();
        mBatchAdapter.notifyDataSetChanged();
        llPosContent.setVisibility(View.VISIBLE);
        tvBatchAmount.setVisibility(View.GONE);
        tvCommodityCode.setTag(false);
        btnPart.setChecked(true);
        btnAll.setChecked(false);

        scanText.setHint("库位");

        if (commodityBean.getRecommendPoslst().isEmpty()) {
            rvBatchList.setVisibility(View.GONE);
            tvPosSetting.setVisibility(View.VISIBLE);
        } else {
            rvBatchList.setVisibility(View.VISIBLE);
            tvPosSetting.setVisibility(View.GONE);
        }
        mAdapter.setNewInstance(commodityBean.getRecommendPoslst());

        tvCommodityName.setText(commodityBean.getCommodityName());
        tvCommodityCode.setText(commodityBean.getBarCode());
        tvPlanAmount.setText(MessageFormat.format("{0}", commodityBean.getPlanDownAmount()));
        tvDownAmount.setText(MessageFormat.format("{0}", commodityBean.getFactDownAmount()));
    }


    @Override
    protected boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onEventCome(Event event) {
        if (event == null) {
            return;
        }
        switch (event.getCode()) {
            case EventConfig.SELECT_BATCH:
                ArrayList<BatchEntity> batchEntities = (ArrayList<BatchEntity>) event.getData();
                setBatchToView(batchEntities);
                verifyData(false);
                success("批次选择成功！");
                break;
        }
    }

    private void setBatchToView(List<BatchEntity> batchEntities) {
        mBatchAdapter.setNewInstance(batchEntities);
        int sum = 0;
        for (int i = 0; i < batchEntities.size(); i++) {
            sum += batchEntities.get(i).getAmount();
        }
        commodityEntity.setDownBatchList(batchEntities);
        tvBatchAmount.setVisibility(View.VISIBLE);
        tvBatchAmount.setText(MessageFormat.format("可下架数量：{0}", sum));
        if (commodityEntity.getPlanDownAmount() > commodityEntity.getFactDownAmount()) {
            etCommodityAmount.setText(Math.min(sum, commodityEntity.getPlanDownAmount() - commodityEntity.getFactDownAmount()) + "");
        } else {
            etCommodityAmount.setText(Math.min(sum, 1) + "");
        }
    }

    @Override
    public <R> LifecycleTransformer<R> toLifecycle() {
        return bindToLifecycle();
    }

    public static BaseViewPagerFragment newInstance(Bundle bundle) {
        ReplenishDownFragment fragment = new ReplenishDownFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @OnClick({R.id.btn_part, R.id.btn_all, R.id.iv_select_batch, R.id.iv_toggle_batch, R.id.btn_submit_and_shelf, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_select_batch:
                if (posBatchEntity == null) {
                    info("请扫描库位后操作！");
                    return;
                }
                if (posBatchEntity.size() == 1) {
                    info("当前库位商品只有一个批次，无需选择！");
                    return;
                }
                SelectBatchActivity.start(getContext(), posBatchEntity, false);
                break;
            case R.id.iv_toggle_batch:
                expandLayout.toggle(true);
                break;
            case R.id.btn_part:
                btnPart.setChecked(true);
                btnAll.setChecked(false);
                break;
            case R.id.btn_all:
                btnPart.setChecked(false);
                btnAll.setChecked(true);
                break;
            case R.id.btn_submit_and_shelf:
            case R.id.btn_submit:
                int amount = NumberUtils.getIntegerValue(etCommodityAmount.getText().toString());
                int sum = 0;
                for (int i = 0; i < mBatchAdapter.getData().size(); i++) {
                    sum += mBatchAdapter.getData().get(i).getAmount();
                }
                if (NumberUtils.getIntegerValue(amount) > sum) {
                    info("下架数量必须小于等于可下架数量:" + sum);
                    return;
                }
                mPresenter.confirmReplenishDown(
                        taskEntity,
                        bindInfoEntity,
                        commodityEntity,
                        ((ArrayList<BatchEntity>) mBatchAdapter.getData()),
                        amount,
                        btnAll.isChecked(),
                        (R.id.btn_submit_and_shelf == view.getId())
                );
                break;
        }
    }
}
